<template>
  <div>
    <van-nav-bar fixed>
      <template #left>
    <img :src="imgObj" alt="" class="logo">
  </template>
  <template #right>
    <van-icon  name="search" size="0.48rem" color="#fff" @click="$router.push('/search')"/>
  </template>
</van-nav-bar>
<van-tabs v-model="channelId"
      animated
      sticky
      offset-top="1.226667rem">
  <van-tab v-for="item in channelList" :key="item.id" :title="item.name" :name="item.id">
<article-list :cid="channelId"/>
  </van-tab>
</van-tabs>
<van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="show = true"/>
<van-popup v-model="show" class="edit_wrap" @closed="onPopupClosed">
      <!-- 弹出层的主体区域 -->
      <channel-edit
      @close="show=false"
      :userChannelList="channelList"
      @addChannel="addChannelFn"
      @removeChannel="removeChannelFn"
      @changeChannel="changeChannelFn"
      ref="channelEdit"
      >
      </channel-edit>
    </van-popup>
  </div>
</template>

<script>
import { userChannelAPI, updateChannelAPI } from '@/api'
import logoPng from '../../assets/toutiao_logo.png'
import ArticleList from './ArticleList.vue'
import ChannelEdit from '@/views/Home/ChannelEdit'

export default {
  components: { ArticleList, ChannelEdit },
  data () {
    return {
      imgObj: logoPng,
      channelList: [],
      channelId: 0,
      show: false // 编辑频道弹出层显示
    }
  },
  async created () {
    const res = await userChannelAPI()
    const { channels } = res.data.data
    this.channelList = channels
  },
  methods: {
    async addChannelFn (val) {
      this.channelList.push(val)
      this.updateChannel()
    },
    removeChannelFn (val) {
      const index = this.channelList.findIndex(item => item.id === val.id)
      this.channelList.splice(index, 1)
      this.updateChannel()
    },
    async  updateChannelFn () {
      const list = this.channelList.filter(item => {
        return item.id !== 0
      })
      const resArr = list.map((item, index) => {
        const newArr = { ...item }
        newArr.req = index + 1
        delete newArr.name
        return newArr
      })
      await updateChannelAPI({
        channels: resArr
      })
    },
    onPopupClosed () {
      this.$refs.channelEdit.isEdit = false
    },
    changeChannelFn (item) {
      this.channelId = item.id
    }
  }
}
</script>

<style scoped lang="less">
.logo {
    width: 100px;
    height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
    padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
